﻿using Cc.Util;
using Magic.Core.Service;
using ManagementTools.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace ManagementTools.Util
{
    internal class MagicHelper
    {
        public static string ErrMsg { get; private set; }
        public static bool? ExistUser(string name)
        {
            string url = App.ApiServer + "/sysUser/Find";
            var list= FindListByField<UserOutput>(url, name);
            if (list == null) return null;
            return list.Count > 0;
        }
        
        public static bool? ExistRole(string name)
        {
            string url = App.ApiServer + "/sysRole/Find";
            var list = FindListByField<RoleOutput>(url, name);
            if (list == null) return null;
            return list.Count > 0;
        }
        public static bool? ExistOrg(string name)
        {
            string url = App.ApiServer + "/sysOrg/Find";
            var list = FindListByField<OrgOutput>(url, name);
            if (list == null) return null;
            return list.Count > 0;
        }
        public static bool? ExistPos(string name)
        {
            string url = App.ApiServer + "/sysPos/Find";
            var list = FindListByField<PosOutputCcj>(url, name);
            if (list == null) return null;
            return list.Count > 0;
        }
        public static bool? ExistEmp(string jobnum)
        {
            string url = App.ApiServer + "/sysEmp/FindJobnum";
            var list = FindListByField<EmpOutput2>(url, jobnum,"Jobnum");
            if (list == null) return null;
            return list.Count > 0;
        }

        /// <summary>
        /// 通过名称查找
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="baseurl">http://localhost:5566/sysUser/Find</param>
        /// <param name="value">要匹配的值</param>
        /// <param name="fieldName">要搜索的字段名，默认为Name</param>
        /// <returns></returns>
        public static List<T> FindListByField<T>(string baseurl, string value,string fieldName="Name")
        {
            string enc = HttpUtility.UrlEncode(value);
            string url = baseurl + $"?{fieldName}={enc}";
            if (!ExecuteHttpReturnData<string, List<T>>(url, RequestType.Get, App.Token, out List<T> list, ""))
                return null;
            return list;
        }
        /// <summary>
        /// 通用HTTP响应，避免重复写同样的代码
        /// </summary>
        /// <typeparam name="Tx">在POST，PUT，DELETE方法中适用，get方法随便给一个类就行</typeparam>
        /// <typeparam name="Tr">响应类型</typeparam>
        /// <param name="url"></param>
        /// <param name="method">HTTP方法</param>
        /// <param name="token">访问令牌，不需令牌时输入空值</param>
        /// <param name="respObj">响应数据，Tx类型</param>
        /// <param name="requestObj">要发送的数据</param>
        /// <returns>成功返回true, 否则false,并输出ErrMsg</returns>
        public static bool ExecuteHttpReturnData<Tx, Tr>(string url, RequestType method, string token, out Tr respObj, Tx requestObj = null)
            where Tx : class
            where Tr : class
        {
#if DEBUG
            int timeout = 600;
#else
            int timeout=10;
#endif

            respObj = default(Tr);
            string ans = "";
            bool ok = false;
            try
            {
                switch (method)
                {
                    case RequestType.Get:
                        ans = HttpHelper.HttpGet(url, timeout, token);
                        break;
                    case RequestType.Post:
                        ans = HttpHelper.HttpPost(url, requestObj, timeout, token);
                        break;
                    case RequestType.Put:

                        break;
                    case RequestType.Delete:
                        ans = HttpHelper.HttpDelete(url, timeout, token);
                        break;
                    default:
                        break;
                }

                if (string.IsNullOrEmpty(ans))
                {
                    ErrMsg = "系统无响应";
                }
                else
                {
                    var res = JsonConvert.DeserializeObject<HttpResponse>(ans);
                    if (res != null)
                    {
                        if (res.Success)
                        {
                            if (res.Data != null)
                                respObj = JsonConvert.DeserializeObject<Tr>(res.Data.ToString());

                            ok = true;
                        }
                        else
                        {
                            ErrMsg = res.Message;
                        }
                    }
                    else
                    {
                        ErrMsg = "系统响应异常";
                    }
                }
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message + "\r\n" + ex.StackTrace;
            }
            
            return ok;
        }
    }
    internal enum RequestType
    {
        Get,
        Post,
        Put,
        Delete,
    }
}
